// packageCourse/pages/courseDetails/courseDetails.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    current:0,
    titleList:[
      {id:1,title:'课程详情'},
      {id:2,title:'课程列表'},
      {id:3,title:'名师介绍'},
      {id:4,title:'课程评价'}
  ],
    courseInfo:{},//课程信息
    courseVideo:[],//该课程的视频信息
    consultId:"",//心理导师id
    courseConsult:[],
    courseComment:{},
    showLogo:[false,false],
    isCollected: false ,// 添加收藏状态变量，初始为未收藏
    userId:"",
    hasOrder:"",
    hideBottomView:"",
    courseId:""
  },
  //回复显示方法
  showChange(e){
    let index = e.currentTarget.dataset.index;
    let showLogo = this.data.showLogo;
    showLogo[index] =!showLogo[index];
    this.setData({
      showLogo:showLogo
    })
  },
  //切换传下标方法
  chooseItem(e){
    this.setData({
      current:e.target.dataset.index
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad:function(options) {
    let loginUserInfo = getApp().globalData.loginUserInfo;
    if (loginUserInfo==null) {
      //没有登录跳转到登录页面
      wx.redirectTo({
        url: '/packageMy/pages/login/login?backUrl=/pages/my/my',
      })
    }
    this.loadPageData(options,this);
    const app = getApp();
    this.setData({
      courseId:options.id,
      userId: app.globalData.loginUserInfo.id
    })
  },
loadPageData(options,that) {
  wx.request({
    url: 'http://localhost:8081/sfzy/course/'+options.id,
    success:(res)=>{
      let courseInfo = res.data.data;
          // 假设totalTime是毫秒数，进行时间格式转换
          let totalSeconds = Math.floor(courseInfo.totalTime / 1000);
          let hours = Math.floor(totalSeconds / 3600);
          totalSeconds %= 3600;
          let minutes = Math.floor(totalSeconds / 60);
          let seconds = totalSeconds % 60;
          courseInfo.totalTime = `${hours}时${minutes}分${seconds}秒`;
          this.setData({
              courseInfo: courseInfo,
              consultId:res.data.data.tutorId
          })
          wx.request({
            url: 'http://localhost:8081/sfzy/consult/'+this.data.consultId,
            method:'GET',
            success:(res)=>{
              this.setData({
                courseConsult:res.data.data
              })
            }
          })
    }
  })
  wx.request({
    url: 'http://localhost:8081/sfzy/courseVideo/page?courseId='+options.id,
    success:(res)=>{
      let courseVideo = res.data.data.list;
      // 使用map方法处理数组元素，返回新的处理后的数组
      courseVideo = courseVideo.map(item => {
          let totalSeconds = Math.floor(item.videoTime / 1000);
          let hours = Math.floor(totalSeconds / 3600);
          totalSeconds %= 3600;
          let minutes = Math.floor(totalSeconds / 60);
          let seconds = totalSeconds % 60;
          return {
            id:item.id,
            videoTitle:item.videoTitle,
            videoUrl:item.videoUrl,
            videoTime: `${hours}时${minutes}分${seconds}秒`
          };
      });
      this.setData({
          courseVideo: courseVideo
      });
    }
  })
  wx.request({
    url: 'http://localhost:8081/sfzy/courseComment/page?pageNum=1&pageSize=2&courseId='+options.id,
    method:'GET',
    success:(res)=>{
      let courseComment = res.data.data.list;
      // 遍历课程评价数据列表，为每个评价添加根据评分生成的星星显示逻辑
      courseComment.forEach(item => {
          let score = item.score;
          let stars = [];
          for (let i = 0; i < 5; i++) {
              if (i < score) {
                  stars.push({ type: 'yellow' }); // 黄色星
              } else {
                  stars.push({ type: 'gray' }); // 灰色星
              }
          }
          item.stars = stars;
      });
      this.setData({
          courseComment: courseComment,
      })
    }
  })
},
goToVideoPlayPage(e) {
  const videoId = e.currentTarget.dataset.id;
  const courseId = this.data.courseInfo.id;
  if (this.data.hideBottomView) {
    // 已购买，执行原有逻辑，先增加学习计数，再进行页面跳转
    wx.request({
      url: 'http://localhost:8081/sfzy/course/increaseLearningCount/' + courseId,
      method: 'POST',
      success: (res) => {
        wx.navigateTo({
          url: `/packageCourse/pages/courseVideo/courseVideo?id=${videoId}` // 这里的videoPlay页面路径根据实际情况修改
        }); 
      },
    });
  } else {
    // 未购买，给出提示，不进行页面跳转
    wx.showToast({
      title: '未购买，无法学习',
      icon: 'none',
      duration: 2000
    });
  }
},
toggleCollection() {
  const courseId = this.data.courseInfo.id;
  const userId = this.data.userId;
  const isCollected = this.data.isCollected;
      wx.request({
          url: `http://localhost:8081/sfzy/courseCollection/page?courseId=${courseId}&userId=${this.data.userId}`,
          method: 'GET',
          success: (res) => {
              if (res.data.data && res.data.data.list.length > 0) {
                    let collectId = res.data.data.list[0].id;
                    // 根据当前状态决定是取消收藏还是恢复收藏
                    if (isCollected) {
                        // 已收藏，执行取消收藏操作（将del字段改为1）
                        wx.request({
                            url: 'http://localhost:8081/sfzy/courseCollection',
                            method: 'PUT',
                            data: {
                                id:collectId,
                                courseId:courseId,
                                userId:userId,
                                del: 1
                            },
                            success: (res) => {
                                if (res.data.code === 200) {
                                    this.setData({
                                        isCollected: false
                                    });
                                    // 收藏状态改变成功后，重新加载课程数据
                                    this.loadPageData(this.options, this);
                                }
                            },
                        });
                    } else {
                         // 未收藏，执行恢复收藏操作（将del字段改为0）
                         wx.request({
                          url: 'http://localhost:8081/sfzy/courseCollection',
                          method: 'PUT',
                          data: {
                              id:collectId,
                              courseId:courseId,
                              userId:userId,
                              del: 0
                          },
                          success: (res) => {
                              if (res.data.code === 200) {
                                  this.setData({
                                      isCollected: true
                                  });
                                  // 收藏状态改变成功后，重新加载课程数据
                                  this.loadPageData(this.options, this);
                              }
                          },
                      });
                    }
                } else {
                   // 未收藏，执行添加收藏操作（发送POST请求，携带课程id和用户id）
                    wx.request({
                      url: 'http://localhost:8081/sfzy/courseCollection',
                      method: 'POST',
                      data: {
                          courseId: courseId,
                          userId: this.data.userId
                      },
                      success: (res) => {
                          if (res.data.code === 200) {
                              this.setData({
                                  isCollected: true
                              });
                              // 收藏状态改变成功后，重新加载课程数据
                              this.loadPageData(this.options, this);
                          }
                      },
                  });
                }
            },
        });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const options = this.options;
    this.loadPageData(options, this);
    wx.request({
      url: `http://localhost:8081/sfzy/courseCollection/page?courseId=${options.id}&userId=${this.data.userId}`,
      success: (res) => {
        if (res.data.data && res.data.data.list.length > 0) {
            // 直接获取对应记录的del字段值作为收藏状态
            this.setData({
                isCollected: res.data.data.list[0].del === 0
            });
          } else {
              // 不存在记录则为未收藏状态
              this.setData({
                  isCollected: false
              });
          }
        },
    });
    // 新增的查询订单接口调用逻辑
    wx.request({
      url: `http://localhost:8081/sfzy/courseOrder/page?courseId=${options.id}&userId=${this.data.userId}`,
      method:'GET',
      success: (res) => {
          if (res.data && res.data.data.list[0].orderState==0) {  // 假设接口返回数据中有hasOrder字段表示是否有订单
              this.setData({
                  hasOrder: true
              });
              // 隐藏底部售价和立即支付部分
              this.hideBottomPart();
          } else {
              this.setData({
                  hasOrder: false
              });
          }
      },
    });
  },
  hideBottomPart() {
    this.setData({
        hideBottomView: true
    });
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    const pages = getCurrentPages();
    const prevPage = pages[pages.length - 2]; // 获取上一个页面实例（收藏页面）
    if (prevPage) {
      // 触发自定义事件，你可以自定义事件名称，比如'returnFromDetails'
      prevPage.setData({
        paymentSuccess: true
      });
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})